﻿using System.Threading.Tasks;
using System;
using Microsoft.EntityFrameworkCore;
using Oracle.ManagedDataAccess.Client;
using Microsoft.AspNetCore.Http;
using Simple.Services.System;
using Simple.Services.System.QHSEUser.Models;
using Simple.Services.System.QHSEViolationCategory.Models;

namespace Simple.Services;

public class QHSEViolationCategoryService
{
    private readonly SimpleDbContext _context;
    private readonly CacheService _cacheService;
    public QHSEViolationCategoryService(SimpleDbContext context, CacheService cacheService)
    {
        _context = context;
        _cacheService = cacheService;
    }
    public async Task<List<QHSEViolationCategoryModel>> GetAsync()
    {
        var violationCategories = await _context.Set<QHSESysViolationCategory>().AsNoTracking().ToListAsync();
        return MapperHelper.Map<List<QHSEViolationCategoryModel>>(violationCategories);
    }
    public async Task<PageResultModel<QHSEViolationCategoryModel>> GetPageAsync(QHSEViolationCategoryPageInputModel input)
    {
        var result = new PageResultModel<QHSEViolationCategoryModel>();
        var query = _context.Set<QHSESysViolationCategory>().AsNoTracking().AsQueryable();

        if (!string.IsNullOrEmpty(input.Code))
        {
            query = query.Where(u => EF.Functions.Like(u.Code, $"%{input.Code}%"));

        }


        // 获取总数量
        result.TotalRows = await query.CountAsync();

        // 分页查询
        query = query.OrderBy(u => u.Code).Page(input.PageNo, input.PageSize);
        var violationCategories = await query.ToListAsync();
        result.Rows = MapperHelper.Map<List<QHSEViolationCategoryModel>>(violationCategories);

        result.SetPage(input);
        result.CountTotalPage();

        return result;
    }
    public async Task<QHSEViolationCategoryModel> GetByCodeAsync(string code)
    {
        var query = _context.Set<QHSESysViolationCategory>().AsNoTracking().AsQueryable();

        if (!string.IsNullOrEmpty(code))
        {
            query = query.Where(u => EF.Functions.Like(u.Code, $"%{code}%"));

        }
        var violationCategory = await query.FirstOrDefaultAsync();
        var result = MapperHelper.Map<QHSEViolationCategoryModel>(violationCategory);

        return result;
    }
    public async Task<int> AddAsync(QHSEViolationCategoryModel model)
    {
        var violationCategory = MapperHelper.Map<QHSESysViolationCategory>(model);
        await _context.AddAsync(violationCategory);
        return await _context.SaveChangesAsync();
    }
    public async Task<int> UpdateAsync(QHSEViolationCategoryModel model)
    {

        var violationCategory = await _context.Set<QHSESysViolationCategory>()
            .Where(a => model.Id == a.Id)
            .FirstOrDefaultAsync();

        if (violationCategory == null)
        {
            throw AppResultException.Status404NotFound("找不到记录，更新失败");
        }

        MapperHelper.Map<QHSEViolationCategoryModel, QHSESysViolationCategory>(model, violationCategory);
        _context.Update(violationCategory);
        int ret = await _context.SaveChangesAsync();

        if (ret == 0)
        {
            throw AppResultException.Status200OK("更新记录数为0");
        }

        return ret;
    }

    public async Task<int> DeleteAsync(IEnumerable<string> ids)
    {
        var violationCategories = await _context.Set<QHSESysViolationCategory>()
            .Where(a => ids.Contains(a.Id))
            .ToListAsync();

        _context.RemoveRange(violationCategories);
        int ret = await _context.SaveChangesAsync();
        return ret;
    }

    public async Task<List<AntTreeNode>> GetCategoryTreeAsync()
    {
        var query = _context.Set<QHSESysViolationCategory>().AsNoTracking().AsQueryable();

        var gws = await query
            .OrderBy(m => m.Id)
            .ToListAsync();
        List<TreeNode> nodes = MapperHelper.Map<List<TreeNode>>(gws);

        var builder = AntTreeNode.CreateBuilder(nodes, "0");
        return builder.Build();
    }
    public async Task<List<string>> GetChildren(string name)
    {
        var result = await _cacheService.GetQHSEViolationCategoryAsync(name);
        if (result.Count == 0)
        {
            var violationCategory = await _context.Set<QHSESysViolationCategory>().AsNoTracking()
            .FirstOrDefaultAsync(u => u.Item == name);

            if (violationCategory == null)
            {
                return new List<string>();
            }

            var children = await _context.Set<QHSESysViolationCategory>()
                .AsNoTracking()
                .Where(u => EF.Functions.Like(u.Code, $"{violationCategory.Code}%"))
                .Select(u => u.Item)
                .ToListAsync();
            await _cacheService.SetQHSEViolationCategoryAsync(children, name);
            return children;
        }
        return result;
    }
    public async Task<List<string>> GetChildren(string name,SimpleDbContext context)
    {
        var result = await _cacheService.GetQHSEViolationCategoryAsync(name);
        if (result.Count == 0)
        {
            var violationCategory = await context.Set<QHSESysViolationCategory>().AsNoTracking()
            .FirstOrDefaultAsync(u => u.Item == name);

            if (violationCategory == null)
            {
                return new List<string>();
            }

            var children = await context.Set<QHSESysViolationCategory>()
                .AsNoTracking()
                .Where(u => EF.Functions.Like(u.Code, $"{violationCategory.Code}%"))
                .Select(u => u.Item)
                .ToListAsync();
            await _cacheService.SetQHSEViolationCategoryAsync(children, name);
            return children;
        }
        return result;
    }
    public async Task<List<string>> GetSon(string name)
    {
        var result = await _cacheService.GetQHSEViolationCategorySonAsync(name);
        if (result.Count == 0)
        {
            var violationCategory = await _context.Set<QHSESysViolationCategory>()
                .AsNoTracking()
            .FirstOrDefaultAsync(u => u.Item == name);

            if (violationCategory == null)
            {
                return new List<string>();
            }
            var sons = await _context.Set<QHSESysViolationCategory>().AsNoTracking().Where(u => u.ParentId == violationCategory.Id).Select(u => u.Item).ToListAsync();
            await _cacheService.SetQHSEViolationCategorySonAsync(sons, name);
            return sons;
        }
        return result;
    }
    public async Task<List<string>> GetSon(string name,SimpleDbContext context)
    {
        var result = await _cacheService.GetQHSEViolationCategorySonAsync(name);
        if (result.Count == 0)
        {
            var violationCategory = await context.Set<QHSESysViolationCategory>()
                .AsNoTracking()
            .FirstOrDefaultAsync(u => u.Item == name);

            if (violationCategory == null)
            {
                return new List<string>();
            }
            var sons = await context.Set<QHSESysViolationCategory>().AsNoTracking().Where(u => u.ParentId == violationCategory.Id).Select(u => u.Item).ToListAsync();
            await _cacheService.SetQHSEViolationCategorySonAsync(sons, name);
            return sons;
        }
        return result;
    }

}
